<?php

/*
 * @Date: 2025-08-19 22:05:25
 * @LastEditors: 贾二小 erxiao.jia@outlook.com
 * @LastEditTime: 2025-10-15 23:09:19
 * @FilePath: /admin-api/app/Http/Controllers/RoleController.php
 */

namespace App\Http\Controllers;

use App\Http\Requests\StoreRoleRequest;
use App\Http\Requests\UpdateRoleRequest;
use App\Http\Resources\RoleResource;
use App\Models\Role;
use Illuminate\Support\Facades\Request;

class RoleController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $roles = Role::key(request('key'))->latest()->paginate(request('per_page', 15));
        return RoleResource::collection($roles);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(StoreRoleRequest $request, Role $role)
    {
        $role->fill($request->input() + ['guard_name' => 'sanctum'])->save();
        return $this->success('添加成功', data: $role);
    }

    /**
     * Display the specified resource.
     */
    public function show(Role $role)
    {
        return $this->success(data: new RoleResource($role));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateRoleRequest $request, Role $role)
    {
        $role->fill($request->input())->save();
        return $this->success('更新成功');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Role $role)
    {
        $role->delete();
        return $this->success(message: '删除成功');
    }

    public function permissions(Role $role)
    {
        return $this->success(data: $role->permissions->pluck('id'));
    }

    public function syncPermissions(Role $role)
    {
        $role->permissions()->sync(request()->input('permissions', []));
        return $this->success('更新成功');
    }

    public function role()
    {
        return $this->success(data: Role::select('id as value', 'name as label')->get());
    }

}
